package net.lanelife.casino.caipiao.service.award;

import java.util.Arrays;
import java.util.List;

import net.lanelife.casino.caipiao.entity.BetRecord;
import net.lanelife.casino.caipiao.entity.BetRecord_;
import net.lanelife.casino.caipiao.entity.GameType;
import net.lanelife.casino.caipiao.entity.LotteryNumber;
import net.lanelife.casino.caipiao.service.api.IAwardService;
import net.lanelife.casino.caipiao.service.api.IBetRecordService;
import net.lanelife.casino.caipiao.service.api.ILotteryNumberService;
import net.lanelife.casino.common.repository.DynamicSpecifications;
import net.lanelife.casino.common.repository.SearchFilter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class AwardService implements IAwardService {
	
	private static final Log LOGGER = LogFactory.getLog(AwardService.class);
	
	@Autowired
	private ILotteryNumberService lotteryNumberService;
	
	@Autowired
	private IBetRecordService betRecordService;
	
	@Autowired
	private BetGroupAwarder betGroupAwarder;

	public void award(GameType gameType, String issue, String number) throws Exception {
		
		Integer gameId = gameType.getId();
		
		LotteryNumber lotteryNumber = lotteryNumberService.find(gameType.getId(), issue);

		// 验证开奖号码状态
		if (!(lotteryNumber.getStatus() == LotteryNumber.Status.UNAWARD || lotteryNumber.getStatus() == LotteryNumber.Status.AWARDFAIL)) {

			// throw new LotteryNumberStatusNotUnawardOrAwardfailException();

		}
		
		// 开启新事务更新开奖号码记录：开奖号码，开奖状态（派奖中）
		lotteryNumber.setLotteryNumber(number);
		lotteryNumber.setStatus(LotteryNumber.Status.AWARDING);
		lotteryNumberService.update(lotteryNumber);
		
		try {
			// 查询该彩种该期的未撤单且未派奖的注单
			Specification<BetRecord> spec = DynamicSpecifications.bySearchFilter(Arrays.asList(
					new SearchFilter(BetRecord_.gameId.getName(), SearchFilter.Operator.EQ, gameId),
					new SearchFilter(BetRecord_.issue.getName(), SearchFilter.Operator.EQ, issue),
					new SearchFilter(BetRecord_.orderStatus.getName(), SearchFilter.Operator.EQ, BetRecord.OrderStatus.NORMAL),
					new SearchFilter(BetRecord_.awardStatus.getName(), SearchFilter.Operator.EQ, BetRecord.OrderStatus.NORMAL)
			));
			List<BetRecord> betRecords = betRecordService.findAll(spec);
			// 按用户分组进行派奖
			BetGroup.award(betGroupAwarder, gameType, lotteryNumber, BetGroup.grouping(betRecords));
			
			LOGGER.info(String.format("%s[%s] 派奖完成：[开奖号码：%s]", gameType.getName(), lotteryNumber.getIssue(), lotteryNumber.getLotteryNumber()));
			
		} catch (Exception e) {
			
			LOGGER.error(String.format("%s[%s] 派奖中断：[开奖号码：%s，异常信息：%s]", gameType.getName(), lotteryNumber.getIssue(), lotteryNumber.getLotteryNumber(), e.getMessage()));
			
		} finally {
			
		}

	}

}
